package lims.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import lims.client.LimsService.LimsHttpResponse;

import org.apache.http.HttpResponse;
import org.fit.cssbox.io.DocumentSource;
import org.fit.net.DataURLHandler;

import com.mchange.v1.io.InputStreamUtils;


public class LimsHTMLSource extends DocumentSource{

	public URL baseURL=null;
	public String urlString=null;
	private String contentType=null;
	private URL url=null;
	private InputStream inputStream;
	 
	public LimsHTMLSource(URL baseURL,String urlString,InputStream stream,String contentType) throws IOException {
		super(baseURL,null);
		url = DataURLHandler.createURL(baseURL,urlString);
        byte[] buffer=InputStreamUtils.getBytes(stream);
		inputStream=new ByteArrayInputStream(buffer);
		this.contentType=contentType;
	}

	
	public LimsHTMLSource(URL baseURL,String urlString) throws IOException {
		super(baseURL,urlString);
        url = DataURLHandler.createURL(baseURL,urlString);
        String ustring=null;
        if(url.getPort()==-1){
        	ustring=String.format("http://%s%s",url.getHost(),url.getPath());
        }else{
        	ustring=String.format("http://%s:%d%s",url.getHost(),url.getPort(),url.getPath());
        }
        if(url.getQuery()!=null) ustring=ustring.concat(String.format("?%s",url.getQuery()));
        try {
			LimsHttpResponse response=LimsService.getInstance().httpGet(ustring);
			int status=response.statusCode;
			if(status==200){
				setContentType(response.contentType);
				byte[] buffer=InputStreamUtils.getBytes(response.content);
				inputStream=new ByteArrayInputStream(buffer);
			}else throw new IOException("http response code error");
		} catch (Exception e) {			
			e.printStackTrace();
			throw new IOException(e.getMessage());
		}
	}

	@Override
	public URL getURL() {
		return url;
	}

	@Override
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType){
		this.contentType=contentType;
	}

	@Override
	public InputStream getInputStream() throws IOException {		
		return inputStream;
	}

	@Override
	public void close() throws IOException {
		if(inputStream!=null) inputStream.close();		
	}


}
